<?php

namespace App\Repositories;

use App\Http\Model\CustRecharge;
use Illuminate\Container\Container as Application;
use Illuminate\Support\Facades\DB;
use App\Repositories\Recharge\Jinmi;
use App\User;
use App\Http\Model\CustAccountFlow;
use App\Http\Model\MemberAgentRelation;

class RechargeRepository extends Base
{
    private $notifyUrl = "";
    private $returnUrl = "";
    private $sms = null;

    public function __construct(Application $app, SmsRepository $sms)
    {
        parent::__construct($app);

        $agent = getAgent();
        $isMobile = isMobile();
        $this->notifyUrl = PC_SITE_URL . "/v1/rechargeNotify";
        $this->returnUrl = $isMobile ? "http://" . $agent->mobile_domain : "http://" . $agent->web_domain;

        $this->sms = $sms;
    }

    /**
     * 线下转账
     * @param $user
     * @param $data
     * @return mixed
     */
    public function offlineTransfer($user, $data)
    {
        $agent = getAgent();
        $data = array_merge($data, [
            "cust_id" => $user->id,
            "type" => 1,
            "status" => 4,
            "agent_id" => $agent ? $agent->id : null,
        ]);

        return CustRecharge::create($data);
    }

    /**
     * 网银支付
     * @param $user
     * @param $money
     * @param $bankId
     * @return bool|string
     */
    public function onlineBanking($user, $money, $bankId)
    {
        $agent = getAgent();
        $orderNumber = $this->makeOrderNumber();
        $money = sprintf("%.2f", $money);
        $data = [
            "money" => $money,
            "bankId" => $bankId,
            "billNumber" => $orderNumber,
            "goodsSubject" => "充值",
            "notifyUrl" => $this->notifyUrl,
            "returnUrl" => $this->returnUrl,
        ];

        $html = Jinmi::onlineBanking($data);
        if (!$html) return false;

        $ret = CustRecharge::create([
            "cust_id" => $user->id,
            "order_number" => $orderNumber,
            "type" => 3,    //jinmi网银支付
            "status" => 0,
            "amount_of_account" => $money,
            "agent_id" => $agent ? $agent->id : null,
        ]);
        return $ret ? $html : false;
    }

    /**
     * 快捷支付
     * @param $user
     * @param $money
     * @return bool|string
     */
    public function quickPayment($user, $money)
    {
        $agent = getAgent();
        $orderNumber = $this->makeOrderNumber();
        $money = sprintf("%.2f", $money);
        $data = [
            "money" => $money,
            "billNumber" => $orderNumber,
            "goodsSubject" => "充值",
            "notifyUrl" => $this->notifyUrl,
            "returnUrl" => $this->returnUrl,
            "userId" => $user->id,
        ];

        $html = Jinmi::quickPayment($data);
        if (!$html) return false;

        $ret = CustRecharge::create([
            "cust_id" => $user->id,
            "order_number" => $orderNumber,
            "type" => 4,    //jinmi快捷支付
            "status" => 0,
            "amount_of_account" => $money,
            "agent_id" => $agent ? $agent->id : null,
        ]);
        return $ret ? $html : false;
    }

    /**
     * 支付回调
     * @param $orderNumber
     * @param $money
     * @param $status
     * @param string $systemOrderNumber
     * @return bool
     */
    public function notify($orderNumber, $money, $status, $systemOrderNumber = "")
    {
        if (!Jinmi::checkNotify()) {
            return false;
        }

        $isPaySuccess = Jinmi::isPaySuccess($status);
        $order = CustRecharge::where("order_number", $orderNumber)->where("status", 0)->first();

        if (!$order) {
            return false;
        }

        // 支付失败
        if (!$isPaySuccess) {
            return $order->update(["status" => 2]);
        }

        $user = User::where("id", $order->cust_id)->first();
        if (!$user) {
            \Log::info(request()->all());
            return false;
        }

        DB::beginTransaction();
        try {
            // 锁行
            DB::select("select * from u_customer where id={$user->id} for update");

            $ret1 = $order->update(["status" => 1, "arrival_time" => date("Y-m-d H:i:s")]);

            $oldBalance = $user->cust_capital_amount;
            $balance = $oldBalance + $order->amount_of_account;
            $ret2 = $user->update(["cust_capital_amount" => $balance]);

            $flowData = [
                "cust_id" => $user->id,
                "flow_type" => 1,
                "amount_of_account" => $order->amount_of_account,
                "account_left" => $balance,
                "remark" => "用户充值",
                "occur_time" => date("Y-m-d H:i:s"),
                "created_time" => date("Y-m-d H:i:s"),
                "flow_id" => $orderNumber,
            ];
            $relation = MemberAgentRelation::where("cust_id", $user->id)->first();
            if ($relation) {
                $flowData = array_merge($flowData, [
                    "emp_agent_id" => $relation->belong_to_agent,
                    "emp_id" => $relation->direct_emp_id,
                    "agent1" => $relation->agent1,
                    "agent2" => $relation->agent2,
                    "agent3" => $relation->agent3,
                    "agent4" => $relation->agent4,
                    "agent5" => $relation->agent5,
                ]);
            }
            $ret3 = CustAccountFlow::create($flowData);

            if ($ret1 && $ret2 && $ret3) {
                DB::commit();
                //TODO 补穿仓补息
                if ($oldBalance < 0) {
                    $ret = requestJava(JAVA_API_URL . "/repay", [
                        custId => $user->id,
                        availableAmount => $order->amount_of_account
                    ]);
                }

                //发送短信
                $this->sms->rechargeSuccess($user->cellphone, $order->amount_of_account);
                return true;
            }
        } catch (\Exception $e) {
            DB::rollback();
            //记录日志
            \Log::info(request()->all());
            return false;
        }
    }

    private function makeOrderNumber()
    {
        return date("YmdHis") . rand(1000000, 9999999);
    }
}